<template>
  <el-card class="el-card--has-heading success">
    <div slot="header">
      <span>团长信息</span>
      <el-button
        style="float: right; padding: 3px 0"
        type="text"
        @click="onClickCreate"
        v-auth:[$P.business.commander.create]
      >创建团长信息</el-button>
    </div>
    <v-table
      :dataSource="dataSource"
      :columns="filterColumn(columns,[$P.business.commander.update,$P.business.commander.delete])"
      :loading="loading"
      :total="total"
      v-bind="bindProps"
      v-on="bindListeners"
    ></v-table>

    <Modal
      :title="modalTitle"
      :loading="modalLoading"
      :visible.sync="visible"
      :width="$V.size.sm"
      :onOk="handleSubmit"
      :onCancel="handleClose"
      :okText="modalType === 'create' ? $t('createText') : $t('updateText')"
    >
      <CommanderForm :record="record" :communitySelects="communitySelects" ref="form" />
    </Modal>

    <Modal
      title="结算信息"
      okText="结算"
      :loading="clearingModalLoading"
      :visible.sync="clearingVisible"
      :width="$V.size.sm"
      :onOk="handleClearingSubmit"
      :onCancel="handleClearingClose"
    >
      <CommanderClearingForm :record="clearingRecord" ref="clearingForm" />
    </Modal>
  </el-card>
</template>

<script>
import {
  getCommanderList,
  createCommander,
  updateCommander,
  deleteCommander,
  getCommunitySelects,
  getCommanderClearingInfo,
  doCommanderClearing
} from '@/api'

/* components
---------------------------------------------------------------- */
import CommanderForm from './components/CommanderForm'
import CommanderClearingForm from './components/CommanderClearingForm'
import { Query } from '@/mixins'

/* model
---------------------------------------------------------------- */
import { primaryKey } from './model'

export default {
  mixins: [Query('query')],

  data () {
    return {
      total: 0,
      dataSource: [],
      loading: false,
      columns: [
        { prop: 'groupLeaderName', label: '团长姓名' },
        { prop: 'groupLeaderContactNumber', label: '团长联系电话', width: this.$V.cellSize.phone },
        { prop: 'groupLeaderAddressDetails', label: '团长详细地址' },
        { prop: 'groupLeaderCommunityName', label: '团长所属社区' },
        { prop: 'groupLeaderCreateTime', label: '创建时间', width: this.$V.cellSize.date, formatter: row => this.$formatTime(row['groupLeaderCreateTime']) },
        { prop: 'groupLeaderCreateUserName', label: '创建人' },
        { prop: 'groupLeaderUpdateTime', label: '修改时间', width: this.$V.cellSize.date, formatter: row => this.$formatTime(row['groupLeaderUpdateTime']) },
        { prop: 'groupLeaderUpdateUserName', label: '修改人' },
        {
          label: '操作',
          minWidth: this.$V.cellSize.action,

          formatter: this.getActionDecorator([
            {
              icon: 'el-icon-data-analysis',
              action: this.onClickClearing,
              type: 'primary'
            },
            {
              icon: 'el-icon-edit',
              action: this.onClickUpdate,
              auth: this.$P.business.commander.update,
              type: 'primary'
            },
            {
              icon: 'el-icon-delete',
              action: this.onClickDelete,
              auth: this.$P.business.commander.delete,
              type: 'danger'
            }
          ])
        }
      ],
      record: {},
      clearingRecord: {},
      communitySelects: [],

      // -------- Modal ----------
      visible: false,
      modalLoading: false,
      modalType: '',

      clearingVisible: false,
      clearingModalLoading: false

      // -------- !Modal ----------
    }
  },
  methods: {
    // Requests
    // ------------------------------------------
    getCommanderList (fn) {
      return this.Catch(getCommanderList, {
        onOk (res) {
          this.dataSource = res.data.data
          this.total = res.data.total
        }
      })('loading', (fn || this.$noop)(this.query))
    },

    deleteCommander (id, { onOk }) {
      return this.Catch(deleteCommander, {
        onOk
      })(null, id)
    },

    createCommander (data) {
      return this.Catch(createCommander, {
        onOk () {
          this.$message.success(this.$t('createOk'))
          this.getCommanderList()
          this.visible = false
        },
        onError (err) {
          console.log(err)
        }
      })('modalLoading', data)
    },

    updateCommander (id, data) {
      return this.Catch(updateCommander, {
        onOk () {
          this.$message.success(this.$t('updateOk'))
          this.getCommanderList()
          this.visible = false
        }
      })('modalLoading', id, data)
    },

    doCommanderClearing (id, data) {
      return this.Catch(doCommanderClearing, {
        onOk () {
          this.$message.success('结算成功')
          this.getCommanderList()
          this.clearingVisible = false
        }
      })('clearingModalLoading', id, data)
    },

    getCommanderClearingInfo (id, {
      onOk,
      onError
    }) {
      return this.Catch(getCommanderClearingInfo, {
        onOk,
        onError
      })('loading', id)
    },

    /**
     * 社区信息下拉列表
     */
    getCommunitySelects (loading) {
      if (this.communitySelects.length) {
        return Promise.resolve()
      }
      return this.Catch(getCommunitySelects, {
        onOk ({ data }) {
          this.communitySelects = data.map(it => ({
            label: it.communityName,
            value: it.communityId
          }))
        }
      })(loading)
    },

    // Form
    // ------------------------------------------
    ensureAllFormPrepareData () {
      const tasks = [this.getCommunitySelects()]

      return this.Catch(() => Promise.all(tasks), {
        onOk () {},
        onError () {}
      })('loading')
    },

    // Table
    // ------------------------------------------

    onClickDelete (row) {
      this.ConfirmDelete({
        onOk: () =>
          this.deleteCommander(row[primaryKey], {
            onOk () {
              this.$message.success(this.$t('deleteOk'))
              this.getCommanderList()
            }
          })
      })
    },

    async onClickUpdate (row) {
      await this.ensureAllFormPrepareData()
      this.modalType = 'update'
      this.record = row
      this.visible = true
    },

    // 点击结算
    async onClickClearing (row) {
      this.getCommanderClearingInfo(row[primaryKey], {
        onOk ({ data }) {
          this.clearingRecord = {
            ...data,
            groupLeaderId: row[primaryKey]
          }
          this.clearingVisible = true
        }
      })
    },

    async onClickCreate () {
      await this.ensureAllFormPrepareData()
      this.modalType = 'create'
      this.record = {}
      this.visible = true
    },

    // Modal
    // ------------------------------------------
    handleSubmit () {
      this.$refs.form.submit((valid, values) => {
        if (valid) {
          if (this.modalType === 'create') {
            this.createCommander(values)
          } else {
            this.updateCommander(values[primaryKey], values)
          }
        }
      })
    },

    // 关闭modal清理数据
    handleClose () {
      this.visible = false
    },

    handleClearingSubmit () {
      this.$refs.clearingForm.submit((valid, values) => {
        if (valid) {
          this.doCommanderClearing(values[primaryKey], values)
        }
      })
    },

    handleClearingClose () {
      this.clearingVisible = false
    }
  },
  computed: {
    modalTitle () {
      return this.modalType === 'create'
        ? this.$t('createText')
        : this.$t('updateText')
    }
  },
  components: { CommanderForm, CommanderClearingForm },

  created () {
    this.getCommanderList()
    this.inject(this.getCommanderList)
  }
}
</script>
